<template>
  <div class="home">
    <Navbar zIndex="10000">
      <template #right>
        <Icon @click="goSearch" name="search2" color="#fff" size="20" />
      </template>
    </Navbar>
    <VideoSwiper ref="videoSwiperRef">
      <template #left="{ video }">
        <div class="user-info">
          <!-- 是不是你关注的人如果是显示你关注的人如果不是什么都不显示 -->
          <span v-if="video.isFollowing" class="following-tag">你的关注</span>
          <span class="user-address">北京市</span>
          <span class="user-name">{{ video.userNickname }}</span>
          <span class="user-description">{{ video.videoDesc }}</span>
        </div>
      </template>
      <template #right="{ video }">
        <div class="user-actions">
          <div class="user-avatar actions-item" @click.stop="FriendsHomepagePage(video.userId)">
            <img :src="video.userAvatar" alt="avatar" />
            <div class="user-avatar-icon" @click.stop="tabFollow(video.userId, video)">
              <!-- 关注 -->
              <Icon :name="video.isFollowing ? 'dui' : 'add'" color="#fff" size="12" />
            </div>
          </div>
          <div class="like-count actions-item" @click.stop="handleLikeClick(video)">
            <Icon name="xin-2" :color="video.isLiked ? 'red' : '#fff'" size="28" />
            <span>{{ video.likeNum }}</span>
          </div>
          <div class="comment-count actions-item" @click.stop="handleCommentClick(video)">
            <Icon name="pinglun" color="#fff" size="28" />
            <span>{{ video.commentNum }}</span>
          </div>
          <div class="share-count actions-item">
            <Icon name="a-fenxiangweifenxiang" color="#fff" size="22" />
            <span>{{ video.shareNum }}</span>
          </div>
        </div>
      </template>
    </VideoSwiper>
    <!-- 👇 新增：声音授权弹窗 -->
    <div v-if="showSoundPrompt" class="sound-prompt-mask">
      <div class="sound-prompt">
        <p>是否允许播放视频声音？</p>
        <div class="btns">
          <button @click="handleSoundResponse(true)">允许</button>
          <button @click="handleSoundResponse(false)">禁止</button>
        </div>
      </div>
    </div>
    <!-- 评论弹窗 -->
    <CommentModal v-if="showCommentModal" v-model="showCommentModal" :videoId="videoCommentsVideoId" />
    <!-- 登陆弹窗 -->
    <LoginModal v-model="showLoginModal" />
  </div>
</template>

<script setup>
import { ref, computed, defineAsyncComponent, defineOptions, onMounted, onUnmounted, onActivated, watch, nextTick } from 'vue'
import { followFriendUserAPI } from '@/api/search'
import { likeVideoAPI } from '@/api/getcomment'
// 👇 新增：声音相关
import { useSoundStore } from '@/stores/sound'
const soundStore = useSoundStore()
const showSoundPrompt = ref(false)
let soundPromptTimer = null
const videoSwiperRef = ref(null)
onMounted(() => {
  if (!soundStore.userInteracted) {
    soundPromptTimer = setTimeout(() => {
      // 显示弹窗，但不暂停视频
      showSoundPrompt.value = true
      // 确保视频在弹窗出现时仍在播放
      const video = videoSwiperRef.value?.getCurrentVideo?.()
      if (video && video.paused) {
        video.play().catch(err => {
          console.warn('弹窗出现时播放失败:', err)
        })
      }
    }, 1000)
  } else {
      // 用户已经做出过选择，直接应用保存的设置
      const video = videoSwiperRef.value?.getCurrentVideo?.()
      if (video) {
        video.muted = !soundStore.soundEnabled
      }
    }
})

onUnmounted(() => {
  if (soundPromptTimer) clearTimeout(soundPromptTimer)
})

// 当组件从缓存中激活时，恢复视频播放
onActivated(() => {
  // 恢复当前视频的播放
  videoSwiperRef.value?.resumeCurrentVideo()
})
function handleSoundResponse(allow) {
  showSoundPrompt.value = false

  // 👇 获取当前视频并设置声音状态
  const video = videoSwiperRef.value?.getCurrentVideo?.()
  if (video) {
    video.muted = !allow // allow=true → muted=false（有声）
    // 如果视频处于暂停状态，尝试播放
    if (video.paused) {
      video.play().catch(err => {
        console.warn('播放失败:', err)
      })
    }
  }
  
  // 👇 保存用户选择到本地存储
  soundStore.markUserInteracted()
  soundStore.setSoundEnabled(allow)
}





defineOptions({
  name: 'Home',
})
import Navbar from '@/components/common/Navbar.vue'

import VideoSwiper from '@/components/common/VideoSwiper.vue'
import Icon from '@/components/common/Icon.vue'
import { useUserStore } from '@/stores/userinfo'
import { Toast } from '@/utils/showtoast'

const userStore = useUserStore()

// ✅ 安全获取 userId，支持响应式
const userId = computed(() => userStore.userInfo?.userId || '')

// 登录弹窗
const showLoginModal = ref(false)
const LoginModal = defineAsyncComponent(() => import('@/components/authentication/LoginModal.vue'))

// 评论弹窗
const showCommentModal = ref(false)
const videoCommentsVideoId = ref('')
const CommentModal = defineAsyncComponent(() => import('@/components/common/CommentModal.vue'))

// 点赞
const handleLikeClick = async (video) => {
  // ✅ 注意：传入的是整个 video 对象，不是解构后的 { videoId }
  if (!userId.value) {
    showLoginModal.value = true
    videoSwiperRef.value?.pauseCurrentVideo()
    return
  }

  try {
    const res = await likeVideoAPI(userId.value, video.videoId)
    if (res.code === 200) {
      // ✅ 切换当前视频的 isLiked 状态
      video.isLiked = !video.isLiked
      // 可选：更新 likeNum
      if (video.isLiked) {
        video.likeNum = (Number(video.likeNum) + 1).toString()
      } else {
        video.likeNum = Math.max(0, Number(video.likeNum) - 1).toString()
      }
    }
  } catch (err) {
    console.error('点赞失败:', err)
  }
}

// 打开评论
const handleCommentClick = async ({ videoId }) => {
  // ✅ 使用 .value 获取 computed 值
  if (!userId.value) {
    showLoginModal.value = true
    // 禁止声音
    videoSwiperRef.value?.pauseCurrentVideo()
    return
  }
  videoCommentsVideoId.value = videoId
  showCommentModal.value = true
}
// 去搜索
import { useRouter } from 'vue-router'
const router = useRouter()
const goSearch = () => {
  if (!userId.value) {
    showLoginModal.value = true
    return
  }
  router.push({ name: 'search' })
}
// 跳转到好友主页
const FriendsHomepagePage = (userId) => {
  router.push({ path: '/friends', query: { userId } })
}


// 关注
const tabFollow = async (friendUserId, video) => {
  console.log(friendUserId)
  // console.log(1)
  if (!userId.value) {
    showLoginModal.value = true
    return
  }
  try {
    // 先记录当前的状态，用于判断操作类型
    const isFollowing = video.isFollowing

    const res = await followFriendUserAPI(userId.value, friendUserId)
    if (res.code !== 200) {
      Toast(res.msg, {
        position: 'bottom'
      })
      return
    }
    res.data == '关注成功' ? video.isFollowing = true : video.isFollowing = false


    // 根据操作前的状态显示正确的提示信息
    Toast(isFollowing ? '取消关注成功' : '关注成功', {
      position: 'bottom'
    })
  } catch (error) {
    console.log(error)
  }
}
watch(userId, (newId, oldId) => {
  // 从无到有：表示刚登录成功
  if (!oldId && newId) {
    // 关闭登录弹窗（如果还开着）
    showLoginModal.value = false
    // 刷新视频列表，获取 isFollowing 状态
    videoSwiperRef.value?.refresh?.()
  }
})
</script>

<style lang="scss" scoped>
/* 弹窗样式 */
.sound-prompt-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  @include flex-center;
  z-index: 20000;
}

.sound-prompt {
  background: white;
  padding: 20px;
  border-radius: 12px;
  width: 60%;
  text-align: center;
  max-width: 400px;
}

.sound-prompt .btns {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.sound-prompt button {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 6px;
  background: #f0f0f0;
}

.sound-prompt button:first-child {
  background: #1890ff;
  color: white;
}

.user-info {
  width: 75%;
  position: absolute;
  bottom: 70px;
  left: 10px;
  color: $white-color;
  font-size: $font-size-base;
  @include flex-center;
  gap: 8px;
  flex-direction: column;
  text-align: left;
  font-size: $font-size-base;


  .user-address,
  .user-name,
  .user-description,
  .following-tag {
    width: 100%;
    font-size: $font-size-base;

  }

  .user-description {
    @include multi-line-ellipsis(5);
  }

}

.user-actions {
  width: 12%;
  position: absolute;
  bottom: 120px;
  right: 10px;
  color: $white-color;
  font-size: $font-size-base;
  @include flex-between;
  gap: 25px;
  flex-direction: column;

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    // overflow: hidden;
    border: 2px solid $white-color;
    position: relative;

    img {
      border-radius: 50%;

    }

    .user-avatar-icon {
      position: absolute;
      bottom: -10px;
      left: 50%;
      transform: translateX(-50%);
      width: 20px;
      height: 20px;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      // 红色背景
      background-color: red;
    }
  }

  .actions-item {
    @include flex-between;
    flex-direction: column;
    gap: 4px;
  }
}
</style>